package com.wwdx.controller.rest;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wwdx.controller.base.BaseController;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.model.WwdxWeixinUserModel;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import com.wwdx.wechat.WxConstant;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/testCode")
public class TestCodeController extends BaseController {
    /**
     * 查询单本书
     */
//    @RequestMapping("/book")
//    public WwdxBookModel purchase(){
//        Object nolineBookid = valueOperations.get(ConstantHolder.BOOK_ONLINE_BOOKID);
//        System.out.println(nolineBookid);
//        Long bookid = 1539936716L;
//        WwdxBookModel byBookId = wwdxBookService.getByBookId(bookid);
//        System.out.println(byBookId);
//        return byBookId;
//    }
    /**
     * 将书单加入书架
     */
    @RequestMapping("/addBook")
    public void addPurchase(){
        Long a = Long.valueOf(1516959738);
        //课
        List<Long> integers = Lists.newArrayList(1504234687L);
        //书籍
        List<Long> integers2 = Lists.newArrayList(
                150L);
        String unionId = "otItHxA1EX0yWSMBz3EkPmvWUrNA";
        String unionId2 = "otItHxM27s4WNAD9ZunBqLTuxK1o"; //我
        Integer typeKe = 1;     //小课
        Integer typeShu = 2;    //书籍
        //课
//        for (Long productId : integers) {
//            wwdxOrderService.purchase(unionId,productId,typeKe);
//            System.out.println("嘿嘿");
//        }
        //书籍
        for (Long productId : integers2) {
            wwdxOrderService.purchase(unionId,productId,typeShu);
            System.out.println("成功喽2~");
        }
        System.out.println("一共"+integers2.size()+"个");
    }
    /**
     * 添加订阅听书
     */
    @RequestMapping("/addSubscribe")
    public void addSubscribe(){
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
        String appId = miDuWxService.getWxMpConfigStorage().getAppId();
//        params.put("appId",appId);
        params.put("appId","wx91e8b20a8fce5f03");
        List<WwdxWeixinUserModel> wwdxWeixinUserModels = wwdxWeixinUserService.find("from WwdxWeixinUserModel where appid=:appId", params);
        for (WwdxWeixinUserModel wwdxWeixinUserModel : wwdxWeixinUserModels) {
            wwdxWeixinUserModel.setSubscribe(false);
            wwdxWeixinUserService.update(wwdxWeixinUserModel);
        }


        //List<WwdxWeixinUserModel> unionids = wwdxWeixinUserService.find("select unionid from WwdxWeixinUserModel where appid=:appId",params);
//        for (Object wwdxWeixinUserModel : unionids) {
//            String unionid = wwdxWeixinUserModel.toString();
//            setOperations.add(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET, unionid);
//        }
    }

    /**
     * 获取素材列表
     */
    @RequestMapping("/getMaterialList")
    public ResultBean getMaterialList() throws WxErrorException {
        HashMap<String, Object> map = Maps.newHashMapWithExpectedSize(2);
        WxMpMaterialService materialService = miDuWxService.getMaterialService();
        //图文素材列表
        WxMpMaterialNewsBatchGetResult result = materialService.materialNewsBatchGet(0, 10);
        //其他媒体素材列表
        WxMpMaterialFileBatchGetResult voice = materialService.materialFileBatchGet("voice", 0, 10);
        map.put("tuwen",result);
        map.put("qita",voice);
        System.out.println(result);
        return renderSuccess(map);
    }
    /**
     * 发送图文消息
     */
    @RequestMapping("/sendNews")
    public void sendNews() throws WxErrorException {
        WxMpKefuService kefuService = miDuWxService.getKefuService();
//        WxMpKefuMessage message = WxMpKefuMessage.MPNEWS().build();
//        message.setMediaId("ibN-6OyJ8vdm06cFgtaoYc6JmsTjkmhVu2SfBm0n_Wg");
//        message.setToUser("o2UEL0j8A4oLxwamvX45ofEN51mE");
        WxMpKefuMessage message = WxMpKefuMessage.MPNEWS().mediaId("ibN-6OyJ8vdm06cFgtaoYc6JmsTjkmhVu2SfBm0n_Wg")
                .toUser("o2UEL0j8A4oLxwamvX45ofEN51mE")
                .build();
        kefuService.sendKefuMessage(message);
    }

    /**
     * 测试redis时间存储
     */
    @RequestMapping("/dateTest")
    public void dateTest() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = format.parse("2018-11-27");
        Date parse1 = format.parse("2018-12-3");
        long time = parse.getTime();
        long time1 = parse1.getTime();
        String key = "cui";
        setOperations.add(key,time);
        setOperations.add(key,time1);
    }

    @RequestMapping("/getDateTest")
    public void getDateTest() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date parse1 = format.parse("2018-12-4");
        long time1 = parse1.getTime();
        Set<Object> cui = setOperations.members("cui");
        for (Object o : cui) {
            System.out.println(o);
            System.out.println("============");
            Long time = time1-(Long)o;
            Long days = time / (1000 * 60 * 60 * 24);
            System.out.println("相差天数为："+days);
        }
    }
    @RequestMapping("/dateTest2")
    public void dateTest2() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String openid = "otItHxM27s4WNAD9ZunBqLTuxK1o";
        Date parse1 = format.parse("2018-12-1");
        String key = "jun";
        setOperations.add(key,openid+"_"+parse1.getTime());
        Boolean member = setOperations.isMember(key, "*otItHxM27s4WNAD9ZunBqLTuxK1o*");
        System.out.println(member);
    }
    @RequestMapping("/getDateTest2")
    public void getDateTest2() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Set<Object> cui = setOperations.members("jun");
        for (Object o : cui) {
            String s = o.toString();
            String[] split = s.split("_");
            System.out.println(split[0] + "" + split[1]);
            long time = format.parse(format.format(new Date())).getTime();
            Long time1 = Long.valueOf(split[1]);
            Long time2 = time - time1;
            Long days = (time - time1) / (1000 * 60 * 60 * 24);
            System.out.println(split[0]+"相差天数为："+days);
        }
    }
    //测试set集合中是否包含某元素
    @RequestMapping("/test1")
    public void test1() {
        Boolean member = setOperations.isMember(ConstantHolder.USER_CONCERN_TOTAL_COUNT, "otItHxM27s4WNAD9ZunBqLTuxK1o");
        System.out.println(member);
    }

    //发送模板消息
    @RequestMapping("/test2")
    public void test2() throws WxErrorException {
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
        String startTime = format2.format(new Date());
        WxMpTemplateMessage templateMessage5 = WxMpTemplateMessage.builder()
                .templateId("ehcIYZRDf9zX54Ki5POT0WdzKrx2JcrjiN01MqM-jFo").url("https://mp.weixin.qq.com/s?__biz=MzUyMzk1MzExMw==&tempkey=OTg2X3BPdUFzZWFjM2NMY2JyZ2xoMTg2ZDVFdjQ3SlRmZk5KSDhCN1doUWRteVlIenFFOGIxamc0OG5tTURva3c4M0I5eHNORXBUVEtXRGUtWDhKUlVvSndoZU93T09lWk95SEJsWTE3OExYbmI1bjk5QjgtdG1fcm5qU2l5VkFmdmVVLWZJQUdhNWhrZHJ3aHo4bzhoY1VNYTRSX2Z6UW1MQmZGQ0k1SGd%2Bfg%3D%3D&chksm=7a35f78b4d427e9d69f4466e12a2b3dee4985da216c61a22b3fe222a4800c6ecb5e5dbc7f2b7&scene=0&xtrack=1&previewkey=Cj5t896sTumJWr7RzN3BVMNS9bJajjJKzz%252F0By7ITJA%253D#wechat_redirect").toUser("o2UEL0j8A4oLxwamvX45ofEN51mE").build();
        WxMpTemplateData firstData5 = new WxMpTemplateData("first", "2018年只剩二周了，你还可以做这12件事今年不白过!\n","#08664A");
        WxMpTemplateData remarkData5;
        remarkData5 = new WxMpTemplateData("remark", "\n"+"☛☛ 【定制计划】点击消息，立即收藏！");
        templateMessage5.addData(firstData5).addData(remarkData5);
        WxMpTemplateData data9 = new WxMpTemplateData("keyword1", "新用户特惠【专属你的】","#ff0000");
        WxMpTemplateData data10 = new WxMpTemplateData("keyword2", startTime+"","#ff0000");
        templateMessage5.addData(data9).addData(data10);
        miDuWxService.getTemplateMsgService().sendTemplateMsg(templateMessage5);
    }
    //测试set集合中是否包含某元素
    @RequestMapping("/test3")
    public void test3() {

        Boolean aBoolean = hashOperations.hasKey(ConstantHolder.USER_RED_PACKET_COUNT, "otItHxM27s4WNAD9ZunBqLTuxK1o");
        System.out.println(aBoolean);
        if (aBoolean){
            if ("1".equals(hashOperations.get(ConstantHolder.USER_RED_PACKET_COUNT,"otItHxM27s4WNAD9ZunBqLTuxK1o"))){
                System.out.println("有红包");
            }else {
                System.out.println("没有红包");
            }
        }
    }

    //测试set集合中是否包含某元素
    @RequestMapping("/test4")
    public void test4() {
              WwdxWeixinUserModel model = new WwdxWeixinUserModel();
        model.setUnionid("otItHxM27s4WNAD9ZunBqLTuxK1o");model.setGmtCreated(new Date());model.setHeadimgurl("http://thirdwx.qlogo.cn/mmopen/sgxvj8rNiamlOLia3b2BFwP2AgicFH4UEeVqJdRUHBu1PRvSQvYHMicMd1FMnXR6IicFaMic0xXQqLOI4TPkf8tHCdSNVBBSfc6vUV/132");
        model.setNickname("九月系");model.setOpenid("o2UEL0j8A4oLxwamvX45ofEN51mE");
        model.setCity("海淀");model.setAppid("wx91e8b20a8fce5f03");model.setGmtModified(new Date());
        System.out.println(wwdxWeixinUserService.getByOpenId("o2UEL0j8A4oLxwamvX45ofEN51mE")+"===========");
        if (wwdxWeixinUserService.getByOpenId("o2UEL0j8A4oLxwamvX45ofEN51mE")==null) wwdxWeixinUserService.save(model);
    }
    //测试set集合中是否包含某元素
    @RequestMapping("/test5")
    public void test5() {
        Boolean aBoolean = hashOperations.putIfAbsent("jun", "1", "333");
        System.out.println(aBoolean);
        hashOperations.put("jun", "1", "333");
    }
    //发送客服模板消息
    @RequestMapping("/test6")
    public void test6() throws WxErrorException, ParseException {
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
        String startTime = format2.format(new Date());
        String openId = "o2UEL0guIRwoMoo27ZVItgEweE98";
        //第一条消息
        WxMpKefuMessage message2 = new WxMpKefuMessage();
        message2.setMsgType(WxConsts.KefuMsgType.VOICE);
        message2.setToUser(openId);
        message2.setMediaId("ibN-6OyJ8vdm06cFgtaoYc0HMPbgR9DXBwctaPEsqMQ");
        miDuWxService.getKefuService().sendKefuMessage(message2);
        //第二条消息
        WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
        String url="http://img.readerday.com/pullxin/tuwen.png";
        article.setPicUrl(url);
        article.setUrl("https://wx.readerday.com?url=https://wx.readerday.com/smallCourseDetail.html?bookid=1504408007%26videoauthorid=82045%26copywriter=82035");
        article.setTitle("彻底改变悲观人生的幸福经典，改变悲观的思维模式，学会弹性乐观。");
        List<WxMpKefuMessage.WxArticle> articles = Lists.newArrayList(article);
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setToUser(openId);
        message.setMsgType(WxConsts.XmlMsgType.NEWS);
        message.setArticles(articles);
        miDuWxService.getKefuService().sendKefuMessage(message);
        //第三条消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .templateId("ehcIYZRDf9zX54Ki5POT0WdzKrx2JcrjiN01MqM-jFo").url("https://wx.readerday.com?url=https://wx.readerday.com/themeDetail.html?themeId=1504870613").toUser(openId).build();
        WxMpTemplateData firstData = new WxMpTemplateData("first", "读懂自己，漂亮生活：由内而外打造100%优雅女性，让你从路人秒变“女神”\n","#08664A");
        WxMpTemplateData remarkData;
        remarkData = new WxMpTemplateData("remark", "\n"+"☛☛【新课上线】点击消息，5折抢购！");
        templateMessage.addData(firstData).addData(remarkData);
        WxMpTemplateData data = new WxMpTemplateData("keyword1", "【7节女神蜕变攻略课】","#ff0000");
        WxMpTemplateData data2 = new WxMpTemplateData("keyword2", startTime+"","#ff0000");
        templateMessage.addData(data).addData(data2);
        miDuWxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        //第四条消息
        WxMpTemplateMessage templateMessage2 = WxMpTemplateMessage.builder()
                .templateId("KZMpl8pvWFCVrbVPG9z5oo5OfunbQMXmvynMVQm74J4").url("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed7380181619ea73&redirect_uri=http%3A%2F%2Fwx.readerday.com%2FcourseList.html&response_type=code&scope=snsapi_userinfo&state=xyz#wechat_redirect").toUser(openId).build();
        WxMpTemplateData firstData2 = new WxMpTemplateData("first","爆款课程折上折：\n\n" +
                "《职场精英阅读成长营》、《如何掌控未来 · 精读计划》、《情商提升课》\n","#08664A");
        WxMpTemplateData remarkData2;
        remarkData2 = new WxMpTemplateData("remark", "\n"+"☛☛【活动仅限今天】点击消息，立即抢购！");
        templateMessage2.addData(firstData2).addData(remarkData2);
        WxMpTemplateData data3 = new WxMpTemplateData("keyword1", "新用户特惠【爆款课程特价】","#ff0000");
        WxMpTemplateData data4 = new WxMpTemplateData("keyword2", startTime+"","#ff0000");
        templateMessage2.addData(data3).addData(data4);
        miDuWxService.getTemplateMsgService().sendTemplateMsg(templateMessage2);
        //第五条消息
        WxMpTemplateMessage templateMessage3 = WxMpTemplateMessage.builder()
                .templateId("KZMpl8pvWFCVrbVPG9z5oo5OfunbQMXmvynMVQm74J4").url("https://mp.weixin.qq.com/s?__biz=MzUyMzk1MzExMw==&tempkey=OTg2X1FFSHRxSWFhUFZwVGVvb3loMTg2ZDVFdjQ3SlRmZk5KSDhCN1doUWRteVlIenFFOGIxamc0OG5tTURvTmdoMXMyaWpNWU9wSEZVRjRRTEltTXZMcTdHaERPZXVRWEFzUVFNOWstaGZMdXM2Z2xnenBTRmZVZ29nVVFnTDlmb3Q2NEs1M2U0MENyUERNb0V1Zkp1U3k2ZVdrZkRvOXczWmtJeGs2TXd%2Bfg%3D%3D&chksm=7a35f78b4d427e9daa918011179dba363c76dc993aae7a00c40d2fbc4e0a1ae2ba7a86cf1b25&scene=0&xtrack=1&previewkey=Cj5t896sTumJWr7RzN3BVMNS9bJajjJKzz%252F0By7ITJA%253D#wechat_redirect").toUser(openId).build();
        WxMpTemplateData firstData3 = new WxMpTemplateData("first", "0.99元秒杀!!\n\n六大领域，18本特价书，低至0.99元，总有一本是你需要的。\n","#08664A");
        WxMpTemplateData remarkData3;
        remarkData3 = new WxMpTemplateData("remark", "\n"+"☛☛【只在今天】点击消息，立即抢购！");
        templateMessage3.addData(firstData3).addData(remarkData3);
        WxMpTemplateData data5 = new WxMpTemplateData("keyword1", "新用户特惠【超级特价日】","#ff0000");
        WxMpTemplateData data6 = new WxMpTemplateData("keyword2", startTime+"","#ff0000");
        templateMessage3.addData(data5).addData(data6);
        miDuWxService.getTemplateMsgService().sendTemplateMsg(templateMessage3);
        //第六条消息
        WxMpTemplateMessage templateMessage5 = WxMpTemplateMessage.builder()
                .templateId("ehcIYZRDf9zX54Ki5POT0WdzKrx2JcrjiN01MqM-jFo").url("https://mp.weixin.qq.com/s?__biz=MzUyMzk1MzExMw==&tempkey=OTg2X3BPdUFzZWFjM2NMY2JyZ2xoMTg2ZDVFdjQ3SlRmZk5KSDhCN1doUWRteVlIenFFOGIxamc0OG5tTURva3c4M0I5eHNORXBUVEtXRGUtWDhKUlVvSndoZU93T09lWk95SEJsWTE3OExYbmI1bjk5QjgtdG1fcm5qU2l5VkFmdmVVLWZJQUdhNWhrZHJ3aHo4bzhoY1VNYTRSX2Z6UW1MQmZGQ0k1SGd%2Bfg%3D%3D&chksm=7a35f78b4d427e9d69f4466e12a2b3dee4985da216c61a22b3fe222a4800c6ecb5e5dbc7f2b7&scene=0&xtrack=1&previewkey=Cj5t896sTumJWr7RzN3BVMNS9bJajjJKzz%252F0By7ITJA%253D#wechat_redirect").toUser(openId).build();
        WxMpTemplateData firstData5 = new WxMpTemplateData("first", "2018年只剩2周了，你还可以做这10件事今年不白过!\n","#08664A");
        WxMpTemplateData remarkData5;
        remarkData5 = new WxMpTemplateData("remark", "\n"+"☛☛ 点击消息，立即收藏！");
        templateMessage5.addData(firstData5).addData(remarkData5);
        WxMpTemplateData data9 = new WxMpTemplateData("keyword1", "新用户特惠【定制计划】","#ff0000");
        WxMpTemplateData data10 = new WxMpTemplateData("keyword2", startTime+"","#ff0000");
        templateMessage5.addData(data9).addData(data10);
        miDuWxService.getTemplateMsgService().sendTemplateMsg(templateMessage5);
        //第七条消息
    }
    @RequestMapping("/test7")
    public void test7() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        valueOperations.set("timecui",format.parse(format.format(new Date())).getTime());
        valueOperations.set("timejun",format.parse(format.format(new Date())).getTime()+"");
        Object timecui = valueOperations.get("timecui");
        System.out.println(timecui.toString());
        Object timejun = valueOperations.get("timejun");
        System.out.println(timejun);
    }
}
